﻿using Dal;
using Entity;
using Model;
using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using Utils;
using Vote.Models;

namespace Bll
{
    public class BllVoteNumber : BllVoteCommon
    {

        private static readonly DalVoteCommon dal = new DalVoteCommon();

        #region 节目(VoteShow)和场次(VoteNumber)信息
        /// <summary>
        /// Redis插入VoteShow
        /// </summary>
        public static void InsertVoteShowToRedis()
        {
            string sql = "select Identify,Id,Name,ImgUrl,Describle,VoteNumberId,Company from VoteShow where IsDelete=0";
            RedisCommon.InsertListToRedis<VoteShowModel>(sql, "VoteShow");
        }

        /// <summary>
        /// Redis插入VoteNumber
        /// </summary>
        public static void InsertVoteNumberToRedis()
        {
            string sql = "select [Id],[Name],[StartTime],[EndTime],[Num],[CreateTime],[IsEffective] from  VoteNumber";
            RedisCommon.InsertListToRedis<VoteNumber>(sql, "VoteNumber");
        }
        /// <summary>
        /// Redis插入VoteVideoUrl
        /// </summary>
        public static void InsertVideoUrlToRedis()
        {
            string sql = "select ShowId,Id,VideoUrl,VideoImageUrl from VoteVideoUrl";
            RedisCommon.InsertListToRedis<VoteVideoUrl>(sql, "VoteVideoUrl");
        }
        #endregion

        #region 关注信息
        /// <summary>
        /// 关注信息
        /// </summary>
        public static void InsertSubcribeToRedis()
        {
            string url = "http://m.gxanr.com/anrweixin/VoteGetopenid.php?act=getall&uniacid=2";
            string json = WebUtils.DoGet(url, null);

            SubscribeResult<List<SubcribeModel>> result = new JavaScriptSerializer().Deserialize<SubscribeResult<List<SubcribeModel>>>(json);

            if (result.status == 200 && result.body != null && result.body.Count > 0)
            {
                var redisClient = RedisManager.GetClient();
                try
                {
                    var vs = redisClient.GetTypedClient<SubcribeModel>();
                    vs.DeleteAll();
                    List<SubcribeModel> listSubcribe = result.body;
                    vs.StoreAll(listSubcribe);
                }
                catch (Exception ex)
                {
                    LogHelper.WriteErrorLog("Redis插入关注信息失败：" + ex.Message);
                }
                finally
                {
                    redisClient.Dispose();
                }
            }
        }

        /// <summary>
        /// 更新单条关注信息
        /// </summary>
        /// <param name="openId"></param>
        /// <param name="flag"></param>
        public static void UpdateOneSubcribeToRedis(string openId, bool flag)
        {
            var redisClient = RedisManager.GetClient();
            try
            {
                var isExists = false; //判断缓存中是否存在当前openId
                var vs = redisClient.GetTypedClient<SubcribeModel>();

                #region 如果缓存里有

                List<string> keyList = vs.GetAllKeys().Where(x => x.Contains("subcribemodel")).ToList();

                foreach (string key in keyList)
                {
                    if (key.Contains("subcribemodel"))
                    {
                        SubcribeModel model = vs.GetValue(key);
                        if (!string.IsNullOrEmpty(model.openId) && model.openId.Equals(openId))
                        {
                            if (flag)
                            {
                                //关注
                                model.follow = "1";
                            }
                            else
                            {
                                //取消关注
                                model.follow = "0";
                            }

                            redisClient.Set(key, model);
                            isExists = true;
                            break;
                        }
                    }
                }
                #endregion

                #region 缓存没有
                if (!isExists)
                {
                    SubcribeModel model = new SubcribeModel();
                    if (flag)
                    {
                        model.openId = openId;
                        model.follow = "1";
                    }
                    else
                    {
                        model.openId = openId;
                        model.follow = "0";
                    }
                    vs.Store(model);
                }

                #endregion
              
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrorLog("Redis更新单个关注信息失败：" + ex.Message);
            }
            finally
            {
                redisClient.Dispose();
            }

        }
        #endregion

        #region 用户微信信息

        /// <summary>
        /// 用户微信信息
        /// </summary>
        public static void InsertUserInfoToRedis()
        {
            string domain = ConfigurationManager.AppSettings["APIJSON"];
            string url = domain + "/GetAllUserInfo";
            string json = WebUtils.DoGet(url, null);

            Result<List<UserInfoForVote>> result = new JavaScriptSerializer().Deserialize<Result<List<UserInfoForVote>>>(json);

            if (result.Status == 200 && result.Body != null && result.Body.Count > 0)
            {
                var redisClient = RedisManager.GetClient();
                try
                {
                    var vs = redisClient.GetTypedClient<UserInfoForVote>();
                    vs.DeleteAll();
                    List<UserInfoForVote> listUserInfo = result.Body;
                    vs.StoreAll(listUserInfo);
                }
                catch (Exception ex)
                {
                    LogHelper.WriteErrorLog("Redis插入用户信息失败：" + ex.Message);
                }
                finally
                {
                    redisClient.Dispose();
                }
            }
        }

        #endregion

        #region 全部插入redis
        public static void InsertAllToRedis()
        {
            InsertVoteShowToRedis();
            InsertVoteNumberToRedis();
            // InsertSubcribeToRedis();
            // InsertUserInfoToRedis();
            InsertVideoUrlToRedis();
        }
        #endregion
    }
}
